package rx.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptUtils {
	
	private static final char[] DIGITS = {
        '0', '1', '2', '3', '4', '5', '6', '7',
           '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
	
	public static String getSimpleMd5String(String sourceString){
		String result=null;
		if(sourceString == null) return null;
		MessageDigest md=null;
		try {
			md = MessageDigest.getInstance("MD5");		
			md.update(sourceString.getBytes());
			byte[] digest=md.digest();
			result = new String(digest);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e.getMessage());
		}
		return result;
		
	}
	
	public static String getHexMd5String(String data){
		String result = null;
		MessageDigest md=null;
		try {
			md = MessageDigest.getInstance("MD5");		
			md.update(data.getBytes());
			byte[] digest=md.digest();
			result = new String(encodeHex(digest));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e.getMessage());
		}
		return result;
	}
	
	public static char[] encodeHex(byte[] data) {

        int l = data.length;

           char[] out = new char[l << 1];

           // two characters form the hex value.
           for (int i = 0, j = 0; i < l; i++) {
               out[j++] = DIGITS[(0xF0 & data[i]) >>> 4 ];
               out[j++] = DIGITS[ 0x0F & data[i] ];
           }

           return out;
    }
	
	public static void main(String args[]){
		System.out.println(getHexMd5String("f"));
	}
}
